package communicate;

import intro.ThreadUtil;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 实现一个简单的生产者消费者模式
 * 
 * @author insight
 * @since 2021/8/30
 */
public class ProduceConsumeDemo {
    static ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(5);

    public static void main(String[] args) {
        new Thread(new Cosumer(), "Cosumer").start();
        new Thread(new Producer(), "Producer").start();
    }

    static class Producer implements Runnable {
        @Override
        public void run() {
            int i = 1;
            while (i < 21) {
                try {
                    q.put(i);
                    System.out.println("Produce e: " + i);
                    ++i;
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Cosumer implements Runnable {
        @Override
        public void run() {
            int e;
            try {
                do {
                    e = q.take();
                    System.out.println("Consume e: " + e);
                    ThreadUtil.second(1);
                } while (e < 20);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}